package common

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/gogf/gf/util/gconv"
	"net/http"
	"time"
)

// recover panic
func Recovery() gin.HandlerFunc {
	return func(c *gin.Context) {
		defer func() {
			if err := recover(); err != nil {
				// 返回错误响应给客户端

				c.JSON(http.StatusInternalServerError, map[string]interface{}{
					"code":    http.StatusInternalServerError,
					"message": gconv.String(err),
					"data":    "",
				})

				// 打印错误信息
				fmt.Println(formatErrorTrace(c, err))
				panic(err)
			}
		}()
		c.Next()
	}
}

func formatErrorTrace(c *gin.Context, err interface{}) string {
	errorMessage := fmt.Sprintf("\n\nrecover error trace:\n%s %s\n%s\n%+v", c.Request.Method, c.Request.URL.Path, time.Now().Format("2006-01-02 15:04:05"), err)

	return errorMessage
}
